package com.sky.service.common.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotation.AddAnnotation;
import com.sky.annotation.UpdateAnnotation;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.mapper.common.DishFlavorMapper;
import com.sky.mapper.common.DishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.common.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Override
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.page(dishPageQueryDTO);
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return Result.success(pageResult);
    }

    @Override
    public boolean add(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        int row = dishMapper.add(dish);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && !flavors.isEmpty()){
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
            dishFlavorMapper.addBatch(flavors);
        }
        return row >0;
    }

    @Override
    public Result<DishVO> findById(Long id) {
        DishVO dishVo = dishMapper.findById(id);
        return Result.success(dishVo);
    }

    @Override
    public boolean deleteByIds(List<Long> ids) {
        int row = dishMapper.deleteByIds(ids);
        return row >0;
    }

    @Override
    public boolean update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishFlavorMapper.deleteByDishId(dish.getId());
        if(dishDTO.getFlavors() != null && dishDTO.getFlavors().size() > 0){
            dishDTO.getFlavors().forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
            dishFlavorMapper.addBatch(dishDTO.getFlavors());
        }
        int row = dishMapper.update(dish);
        return row >0;
    }

    @Override
    public boolean startOrStop(Integer status, Long id) {
        int row = dishMapper.startOrStop(status, id);
        return row >0;
    }

    @Override
    public List<Dish> list(Integer categoryId) {
        return dishMapper.list(categoryId);
    }
}
